package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"rbook/api/request"
	"rbook/globals"
	"rbook/intermal/model"
	"regexp"
	"time"
)

func CommentAdd(c *gin.Context) {
	param := request.Comment{}
	if err := c.ShouldBind(&param); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 400,
			"mes":  "参数错误",
		})
		return
	}
	if param.Content == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 400,
			"mes":  "评论内容需非空",
		})
		return
	}
	if len(param.Content) < 1 && len(param.Content) > 200 {
		c.JSON(http.StatusOK, gin.H{
			"code": 400,
			"mes":  "评论内容需1-200 字",
		})
		return
	}
	compile, _ := regexp.Compile(`https?://`)
	matchString := compile.MatchString(param.Content)
	if matchString == true {
		c.JSON(http.StatusOK, gin.H{
			"code": 400,
			"mes":  "禁止包含链接",
		})
		return
	}

	data := model.Comment{
		ContentId:   param.ContentId,
		UserId:      param.UserId,
		Content:     param.Content,
		CommentTime: time.Now(),
		LikeCount:   param.LikeCount,
	}

	globals.DB.Create(&data)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"mes":  "评论内容添加成功",
		"data": data.Id,
	})
}

func CommentUpdate(c *gin.Context) {
	param := request.CommentUpdate{}
	if err := c.ShouldBind(&param); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 400,
			"mes":  "参数错误",
		})
		return
	}
	data := model.Comment{
		Id:        param.Id,
		LikeCount: param.LikeCount,
	}
	globals.DB.Where("id=?", data.Id).Updates(&data)
	if data.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 400,
			"mes":  "该用户已点赞",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"mes":  "该用户更新成功",
		"data": data.Id,
	})
}
